<template>
  <view class="content">
    <!-- Logged-in state -->
    <view v-if="userInfo && userInfo._id" class="user-info">
      <!-- 背景纹理图片 - 铺满整个区域到精选商品以上 -->
      <view class="page-header-bg">
        <image src="/static/bg.jpg" mode="aspectFill"></image>
      </view>

      <!-- 品牌标题 -->
      <view class="page-header">
        <text class="header-title">左慈太和枕</text>
        <text class="header-subtitle">内在的平和是抵御外邪的根本</text>
      </view>

      <!-- 小店商品展示 -->
      <view class="product-section">
        <!-- 商品标题 - 简约设计 -->
        <view class="product-header">
          <text class="product-title">精选商品</text>
          <text class="product-subtitle">左右滑动查看更多</text>
        </view>

        <!-- 商品轮播容器 - 简约灰白边框 -->
        <view class="product-swiper-container">
          <swiper
            class="product-swiper"
            :indicator-dots="true"
            :autoplay="false"
            :duration="500"
            :circular="true"
            indicator-color="rgba(0, 0, 0, 0.2)"
            indicator-active-color="#333333"
            @change="onProductSwiperChange"
          >
            <swiper-item v-for="(product, index) in productList" :key="index">
              <view class="product-item">
                <store-product
                  class="store-product-card"
                  appid="wx64874b77c972fb53"
                  :product-id="product.id"
                  :custom-style="productCustomStyle"
                  @entersuccess="onProductEnterSuccess"
                  @entererror="onProductEnterError"
                ></store-product>
              </view>
            </swiper-item>
          </swiper>
        </view>
      </view>

      <!-- 产品视频轮播 -->
      <view class="video-section">
        <view class="video-tip">
          <text class="tip-icon">📺</text>
          <text class="tip-text">产品介绍视频</text>
          <text class="tip-sub">（点击观看详情）</text>
        </view>

        <view class="video-swiper-container">
          <swiper
            class="video-swiper"
            :indicator-dots="true"
            :autoplay="true"
            :interval="3000"
            :duration="500"
            :circular="true"
            indicator-color="rgba(255, 255, 255, 0.5)"
            indicator-active-color="#4a7c59"
          >
            <swiper-item v-for="(video, index) in videoList" :key="index">
              <view class="video-item">
                <channel-video
                  class="product-video"
                  :feed-token="video.token"
                  :autoplay="false"
                  :loop="true"
                  object-fit="contain"
                  @error="onVideoError"
                ></channel-video>
              </view>
            </swiper-item>
          </swiper>
        </view>
      </view>

      <!-- 今日养生贴士 -->
      <view class="daily-tip">
        <view class="tip-icon">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z" fill="#4a5d23" />
          </svg>
        </view>
        <text class="tip-title">承古法，养天年</text>
        <text class="tip-content"> 源自丹鼎派祖师左慈的养生智慧，我们并非简单复刻，而是将“金丹”的炼养哲学，转化为现代人触手可及的日常养生。每一只枕头，都承载着我们对自然与和谐的敬畏。</text>
      </view>

      <!-- 分享按钮 -->
      <button class="share-button" open-type="share">
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M15 12c-1.1 0-2.1.4-2.8 1.1L7.9 10.6c.1-.3.1-.6.1-.9s0-.6-.1-.9l4.3-2.5C12.9 7.6 13.9 8 15 8c2.2 0 4-1.8 4-4s-1.8-4-4-4-4 1.8-4 4c0 .3 0 .6.1.9L6.8 7.4C6.1 6.6 5.1 6.2 4 6.2c-2.2 0-4 1.8-4 4s1.8 4 4 4c1.1 0 2.1-.4 2.8-1.1l4.3 2.5c-.1.3-.1.6-.1.9 0 2.2 1.8 4 4 4s4-1.8 4-4-1.8-4-4-4z"
            fill="white" />
        </svg>
        分享给好友
      </button>
    </view>

    <!-- Login form state -->
    <view v-else class="login-form">
      <!-- 品牌logo -->
      <view class="login-logo">
        <view class="logo-icon-large">
          <svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="40" cy="40" r="40" fill="#4a5d23" />
            <path d="M25 45c0-10 7-20 15-20s15 10 15 20c0 4-3 7-7 7H32c-4 0-7-3-7-7z" fill="white" />
            <path d="M32 32c3-3 5-4 8-4s5 1 8 4" stroke="white" stroke-width="2" fill="none" />
          </svg>
        </view>
      </view>

      <view class="form-title">欢迎回来，{{ tempNickname || '养生达人' }}</view>
      <view class="form-tip">愿您每晚都有好梦</view>

      <view class="avatar-wrapper">
        <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="avatar" :src="tempAvatarUrl || '/static/logo.png'"></image>
        </button>
      </view>

      <view class="nickname-wrapper">
        <text class="nickname-label">昵称</text>
        <input class="nickname-input" type="nickname" placeholder="请在此输入或确认您的昵称" @change="onNicknameChange" />
      </view>

      <button type="primary" class="login-btn" @click="submitLogin">授权并登录</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: null,
      tempAvatarUrl: '', // For storing the temporary path of the chosen avatar
      tempNickname: '', // For storing the user's nickname from the input
      // 商品列表（4个商品）
      productList: [
        { id: '10000183888502' }, // 新增商品1
        { id: '10000305678831' }, // 新增商品2
        { id: '10000212924865' }, // 原来的商品
        { id: '10000325758974' }  // 新增商品3
      ],
      currentProductIndex: 0, // 当前商品索引
      // 小店商品自定义样式
      productCustomStyle: {
        card: {
          'background-color': '#FFFFFF',
        },
        title: {
          color: '#333333',
        },
        price: {
          color: '#4a7c59'
        },
        'buy-button': {
          width: '140rpx',
          'border-radius': '50rpx',
          'background-color': '#4a7c59',
          color: '#FFFFFF',
        },
        'buy-button-disabled': {
          width: '140rpx',
          'border-radius': '50rpx',
          'background-color': '#CCCCCC',
          color: '#FFFFFF',
        },
      },
      // 视频列表
      videoList: [
        { token: 'token/AWFb30aKR' },
        { token: 'token/AEdtg9M1B' },
        { token: 'token/A12kKz8FD' }
      ]
    }
  },
  onShareAppMessage() {
    if (!this.userInfo || !this.userInfo._id) {
      console.error('无法生成分享链接：用户信息不完整');
      return {
        title: '这款安神枕，让你睡个好觉！',
        path: '/pages/index/index' // 默认分享到首页
      };
    }
    const sharePath = `/pages/landing/landing?promoter_id=${this.userInfo._id}`;
    return {
      title: '芳香通窍，宁心好眠！这个枕头太棒了，送你20元优惠券！',
      path: sharePath,
    };
  },
  onLoad() {
    // Attempt to restore user info from local storage
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userInfo = userInfo;
    }
  },
  methods: {
    // 商品轮播切换事件
    onProductSwiperChange(e) {
      this.currentProductIndex = e.detail.current;
      console.log('当前商品索引:', this.currentProductIndex);
    },
    // 小店商品事件处理
    onProductEnterSuccess(e) {
      console.log('跳转小店成功:', e);
    },
    onProductEnterError(e) {
      console.error('跳转小店失败:', e.detail);
      uni.showToast({
        title: e.detail.message || '跳转失败',
        icon: 'none'
      });
    },
    // 视频错误处理
    onVideoError(e) {
      console.error('视频加载失败:', e);
    },
    onChooseAvatar(e) {
      // Get the temporary path of the avatar
      this.tempAvatarUrl = e.detail.avatarUrl;
    },
    onNicknameChange(e) {
      // Get the nickname value
      this.tempNickname = e.detail.value;
    },
    async submitLogin() {
      if (!this.tempAvatarUrl) {
        uni.showToast({ title: '请选择头像', icon: 'none' });
        return;
      }
      if (!this.tempNickname) {
        uni.showToast({ title: '请输入昵称', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '登录中...' });

      try {
        // 1. Upload the avatar to uniCloud storage
        const uploadResult = await uniCloud.uploadFile({
          filePath: this.tempAvatarUrl,
          cloudPath: `user-avatars/${Date.now()}-${Math.random().toString(36).substring(2)}.jpg`,
          cloudPathAsRealPath: true,
        });

        // The permanent URL of the uploaded image
        const permanentAvatarUrl = uploadResult.fileID;

        // 2. Get the WeChat login code
        const loginRes = await uni.login({
          provider: 'weixin',
        });

        // Prepare parameters for the cloud function
        const callParams = {
          code: loginRes.code,
          userInfo: {
            nickName: this.tempNickname,
            avatarUrl: permanentAvatarUrl, // Use the permanent URL
          },
        };

        // Include promoter_id if it exists
        const promoter_id = uni.getStorageSync('promoter_id');
        if (promoter_id) {
          callParams.promoter_id = promoter_id;
        }

        // 3. Call the cloud function to log in
        const cloudRes = await uniCloud.callFunction({
          name: 'user-center',
          data: {
            action: 'loginByWeixin',
            params: callParams,
          },
        });

        uni.hideLoading();

        // 4. Handle the login result
        if (cloudRes.result && cloudRes.result.uid) {
          console.log('登录成功', cloudRes.result);
          this.userInfo = cloudRes.result.userInfo;
          // Store user info and token in local storage
          uni.setStorageSync('userInfo', cloudRes.result.userInfo);
          uni.setStorageSync('uni_id_token', cloudRes.result.token);
          uni.setStorageSync('uni_id_token_expired', cloudRes.result.tokenExpired);

          // Emit a global event for other pages
          uni.$emit('userLoggedIn', this.userInfo);

          // Clear promoter_id if it was used
          if (cloudRes.result.promoterBinded) {
            console.log('推荐关系已绑定，清除本地 promoter_id');
            uni.removeStorageSync('promoter_id');
          }
        } else {
          throw new Error(cloudRes.result.message || '登录失败');
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: `登录失败: ${error.message || '未知错误'}`,
          icon: 'none',
        });
        console.error('登录失败', error);
      }
    },
  },
}
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 40rpx;
  box-sizing: border-box;
  background: linear-gradient(180deg, #f8fdf8 0%, #ffffff 100%);
  min-height: 100vh;
}

/* 页面标题 - 减少高度并移除边框 */
.page-header {
  text-align: center;
  margin-bottom: 20rpx;
  width: 100%;
  position: relative;
  padding: -10rpx 40rpx 5rpx 40rpx;
  z-index: 2;
}

/* 背景纹理层 - 铺满整个区域到精选商品以上 */
.page-header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
  /* 设置最小高度，确保背景覆盖到商品区域 */
  min-height: 300rpx;
}

.page-header-bg image {
  width: 100%;
  height: 100%;
  /* 使用混合模式增强纹理效果 */
  mix-blend-mode: multiply;
  opacity: 0.05;
}

/* 渐变遮罩层 - 增强文字可读性和层次感 */
.page-header::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  /* 轻微的渐变遮罩，确保文字清晰 */
  /* background: linear-gradient(135deg,
    rgba(248, 253, 248, 0.7) 0%,
    rgba(255, 255, 255, 0.8) 50%,
    rgba(248, 253, 248, 0.85) 100%); */
}

.header-title {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #2d5a3d;
  letter-spacing: 4rpx;
  margin-bottom: 12rpx;
  position: relative;
  z-index: 3;
  /* 添加微妙的文字阴影增强立体感 */
  text-shadow: 0 2rpx 8rpx rgba(74, 124, 89, 0.1);
}

.header-subtitle {
  display: block;
  position: relative;
  z-index: 3;
  font-size: 26rpx;
  color: #666666;
  letter-spacing: 2rpx;
  /* 添加微妙的文字阴影 */
  text-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.05);
}

/* 小店商品区域 */
.product-section {
  width: 100%;
  margin-bottom: 40rpx;
}

/* 商品标题 - 简约设计 */
.product-header {
  margin-bottom: 24rpx;
}

.product-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8rpx;
  letter-spacing: 1rpx;
}

.product-subtitle {
  display: block;
  font-size: 24rpx;
  color: #999999;
  letter-spacing: 0.5rpx;
}

/* 商品轮播容器 - 简约灰白边框 */
.product-swiper-container {
  width: 100%;
  position: relative;
  border-radius: 16rpx;
  overflow: hidden;
  /* 简约边框效果 */
  border: 2rpx solid #e5e5e5;
  background: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.product-swiper {
  width: 100%;
  height: 420rpx; /* 降低高度 */
  border-radius: 14rpx;
  overflow: hidden;
  background: #ffffff;
}

.product-item {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
}

.store-product-card {
  width: 100%;
  height: 100%;
}

/* 今日养生贴士 */
.daily-tip {
  background: linear-gradient(135deg, #ffffff 0%, #f8fdf8 100%);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  width: 100%;
  box-shadow: 0 8rpx 24rpx rgba(74, 93, 35, 0.1);
  border: 2rpx solid rgba(74, 93, 35, 0.1);
}

.tip-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
}

.tip-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #4a5d23;
  text-align: center;
  display: block;
  margin-bottom: 15rpx;
}

.tip-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.8;
  text-align: left;
}

/* 产品视频区域 */
.video-section {
  width: 100%;
  margin-bottom: 40rpx;
}

.video-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  margin-bottom: 20rpx;
  padding: 16rpx 24rpx;
  background: linear-gradient(135deg, #f8fdf8 0%, #ffffff 100%);
  border-radius: 50rpx;
  border: 2rpx solid rgba(74, 124, 89, 0.15);
}

.video-tip .tip-icon {
  font-size: 28rpx;
}

.video-tip .tip-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #4a7c59;
}

.video-tip .tip-sub {
  font-size: 22rpx;
  color: #999999;
}

.video-swiper-container {
  width: 100%;
  border-radius: 20rpx;
  overflow: hidden;
  /* 专业边框效果 */
  border: 3rpx solid #4a7c59;
  box-shadow:
    0 8rpx 24rpx rgba(74, 124, 89, 0.15),
    0 0 0 6rpx rgba(74, 124, 89, 0.08),
    inset 0 0 0 2rpx rgba(255, 255, 255, 0.5);
  position: relative;
}

/* 添加装饰性边角 */
.video-swiper-container::before,
.video-swiper-container::after {
  content: '';
  position: absolute;
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #4a7c59;
  z-index: 10;
  pointer-events: none;
}

.video-swiper-container::before {
  top: -2rpx;
  left: -2rpx;
  border-right: none;
  border-bottom: none;
  border-top-left-radius: 20rpx;
}

.video-swiper-container::after {
  bottom: -2rpx;
  right: -2rpx;
  border-left: none;
  border-top: none;
  border-bottom-right-radius: 20rpx;
}

.video-swiper {
  width: 100%;
  height: 450rpx;
}

.video-item {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f5f5 0%, #fafafa 100%);
}

.product-video {
  width: 100%;
  height: 100%;
}

/* 分享按钮 */
.share-button {
  background: linear-gradient(135deg, #4a5d23 0%, #5a6d33 100%);
  color: white;
  border-radius: 25rpx;
  padding: 20rpx 40rpx;
  font-size: 30rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  box-shadow: 0 8rpx 24rpx rgba(74, 93, 35, 0.3);
  border: none;
  width: 100%;
}

.share-button::after {
  border: none;
}

/* 登录页面样式 */
.login-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 80rpx;
}

.login-logo {
  margin-bottom: 50rpx;
}

.logo-icon-large {
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #4a5d23;
  margin-bottom: 10rpx;
}

.form-tip {
  font-size: 28rpx;
  color: #8a9a5a;
  margin-bottom: 60rpx;
}

.avatar-wrapper {
  margin-bottom: 50rpx;
}

.avatar-btn {
  padding: 0;
  border: none;
  background-color: transparent;
  border-radius: 50%;
}

.avatar-btn::after {
  border: none;
}

.nickname-wrapper {
  width: 100%;
  display: flex;
  align-items: center;
  background-color: #f8fdf8;
  border: 2rpx solid rgba(74, 93, 35, 0.2);
  border-radius: 15rpx;
  padding: 25rpx;
  margin-bottom: 60rpx;
}

.nickname-label {
  font-size: 30rpx;
  color: #4a5d23;
  font-weight: bold;
  margin-right: 20rpx;
}

.nickname-input {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.login-btn {
  width: 100%;
  background: linear-gradient(135deg, #4a5d23 0%, #5a6d33 100%);
  color: white;
  border-radius: 25rpx;
  font-size: 32rpx;
  font-weight: bold;
  height: 90rpx;
  box-shadow: 0 8rpx 24rpx rgba(74, 93, 35, 0.3);
}

/* 用户信息区域 - 包含整个背景区域 */
.user-info {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 40rpx;
  width: 100%;
  min-height: 400rpx;
}
</style>
